package com.cdut.hezhisu.dribbble;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.Toast;

import com.cdut.hezhisu.dribbble.bean.Works;
import com.cdut.hezhisu.dribbble.util.DownloadTask;
import com.cdut.hezhisu.dribbble.util.PictureUtil;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

public class MainActivity extends Activity {

    private ListView mLvWorks;
    private View mFooterView;
    private PictureListAdapter mAdapter;
    private int mCurPage = 1;
    private boolean mloadMoreEnable = true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mLvWorks = (ListView) findViewById(R.id.picture_list);
        mAdapter = new PictureListAdapter(this);
        mFooterView = LayoutInflater.from(this).inflate(R.layout.layout_list_footer,null);
        mLvWorks.addFooterView(mFooterView);
        mLvWorks.addHeaderView(LayoutInflater.from(this).inflate(R.layout.layout_list_header, null));
        mLvWorks.setAdapter(mAdapter);
        getWorks(mCurPage);
         mLvWorks.setOnScrollListener(new AbsListView.OnScrollListener() {
             @Override
             public void onScrollStateChanged(AbsListView view, int scrollState) {
                 if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE && mloadMoreEnable) {
                     // 判断是否滚动到底部
                     if (view.getLastVisiblePosition() == view.getCount() - 1) {
                         //加载更多功能的代码
                         mCurPage++;
                         getWorks(mCurPage);
                     }
                 }
             }

             @Override
             public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

             }
         });
        mAdapter.setOnClickMenuListener(new PictureListAdapter.OnClickMenuListener() {
            @Override
            public void onClick(String url) {
                String path = DribbbleApp.BASIC_IMAGE_PATH + "/" + System.currentTimeMillis() + ".jpg";
                DownloadTask task = new DownloadTask(url,2,path);
                task.start();
                task.setDownLoadCallBack(new DownloadTask.DownLoadCallBack() {
                    @Override
                    public void onSuccess(String path) {
                        Intent localIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(path)));
                        sendBroadcast(localIntent);
                        Toast.makeText(MainActivity.this, "图片已下载到" + path, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onFail() {
                        Toast.makeText(MainActivity.this, "下载失败", Toast.LENGTH_SHORT).show();
                    }
                });

            }
        });
    }

    public void getWorks(int page){

        AsyncHttpClient client = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.add("page",String.valueOf(page));
        client.get("http://192.168.0.104:5000/works", params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                List<Works> workses = new ArrayList<Works>();
                try {
                    JSONArray array = new JSONArray(response.optString("data"));
                    for(int i = 0; i < array.length(); i++){
                        JSONObject jsonObject = array.getJSONObject(i);
                        Works works = new Works();
                        works.author = "by " + jsonObject.optString("name").trim();
                        works.avatar = jsonObject.optString("avatar");
                        works.describe = jsonObject.optString("describe");
                        works.title = jsonObject.optString("title");
                        works.picUrl = jsonObject.optString("pic_url");
                        works.colors = new ArrayList<String>();
                        JSONArray colors = new JSONArray(jsonObject.optString("colors"));
                        for(int j = 0; j < colors.length(); j++){
                            works.colors.add(colors.getString(j));
                        }
                        workses.add(works);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                mAdapter.addDataList(workses);
                if(workses.size() < 6){
                    mLvWorks.removeFooterView(mFooterView);
                    mloadMoreEnable = false;
                }

            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);

            }
        });


    }


}
